package com.kmxd.ams.infra.jobs;

import cn.hutool.core.util.ObjectUtil;
import com.kmxd.ams.client.system.ISysJobsSvc;
import com.kmxd.ams.core.common.enums.JobsEnum;
import com.kmxd.ams.core.util.RedisUtils;
import com.kmxd.ams.infra.system.entity.SysJobs;
import java.time.LocalDateTime;
import javax.annotation.PostConstruct;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

/**
 * 创建索引任务
 *
 * @author ZuoLG
 */
@Data
@Slf4j
@Component()
public class EsIndexJobs implements SchedulingConfigurer {

  private String cron;
  @Autowired private ISysJobsSvc sysJobsSvc;
  @Autowired private RedisUtils redisUtils;

  @PostConstruct
  public void init() {
    // 定时任务触发，可修改定时任务的执行周期,将表达式配置在数据库中
    SysJobs sysJobs = sysJobsSvc.getJobsByKey(JobsEnum.ES_INDEX_JOBS.getCode());
    if (ObjectUtil.isNotEmpty(sysJobs.getCron())) {
      cron = sysJobs.getCron();
    }
  }

  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    log.info("cron:", cron);
    log.info(taskRegistrar.getScheduledTasks().toString());
    // 动态使用cron表达式设置循环间隔
    taskRegistrar.addTriggerTask(
        this::execute,
        triggerContext -> {
          // 定时任务触发，可修改定时任务的执行周期,将表达式配置在数据库中
          if (ObjectUtil.isNotEmpty(cron)) {
            CronTrigger trigger = new CronTrigger(cron);
            return trigger.nextExecutionTime(triggerContext);
          }
          return null;
        });
  }

  /** 任务调度方法 */
  public void execute() {
    log.info(
        "执行 【开始】【创建索引任务】，线程名：【{}】，时间:【{}】,cron:【{}】",
        Thread.currentThread().getName(),
        LocalDateTime.now().toLocalTime(),
        cron);
  }
}
